#!/usr/bin/env bash
cd `dirname $0`
if [ -f work/runing ];then
    id=`cat work/runing|head -1`
    if [[ "$id" && "`ps -ef|grep "$0"|grep "$id"`" ]];then
        echo "watch已经运行 $id"
        exit 2
    fi
fi
[[ ! -d work ]] && mkdir work
[[ ! -d logs ]] && mkdir logs
echo "$1" > work/runing
force_download="F"
force_update="F"

alias echo="echo $(date "+%Y-%m-%d %H:%M:%S")"
DIRNAME_NOW=`pwd`
NOW_DAY=`date "+%Y-%m-%d"`

download(){
    force_download="F"
    echo "创建下载任务" >> $DIRNAME_NOW/logs/main-$NOW_DAY.log
    [ -f .disable ] && exit 1
    ssh -p 2222 jahv@nas.cjahv.com 'ls /data/update.lock > /dev/null 2>&1'
    if [[ "$?" == "0" ]];then
        echo "存在其他上传任务，本次同步取消" >> $DIRNAME_NOW/logs/main-$NOW_DAY.log
        force_download="T"
        continue
    fi
    bash download.sh > /dev/null
}

update(){
    force_update="F"
    echo "创建上传任务" >> $DIRNAME_NOW/logs/main-$NOW_DAY.log
    [ -f .disable ] && exit 1
    echo "清理日志" >> $DIRNAME_NOW/logs/main-$NOW_DAY.log
    find ./logs -mtime +1 -name '*.log' -exec rm -rf {} \;
    latest_logfile_name=`ls -lt ./logs|grep '\d.log'|head -n 1|awk '{print $9}'`
    if [[ ! "$latest_logfile_name" || "`find ./logs -amin +10 -name '*.log'|grep "${latest_logfile_name}"`" ]];then
        echo "创建上传文件锁" >> $DIRNAME_NOW/logs/main-$NOW_DAY.log
        ssh -p 2222 jahv@nas.cjahv.com 'ls /data/update.lock > /dev/null 2>&1 || (touch /data/update.lock && exit 5)'
        if [[ "$?" == "0" ]];then
            echo "已经存在其他上传任务" >> $DIRNAME_NOW/logs/main-$NOW_DAY.log
            continue
        fi
        bash ./backup.sh > /dev/null
        echo "清除上传文件锁" >> $DIRNAME_NOW/logs/main-$NOW_DAY.log
        ssh -p 2222 jahv@nas.cjahv.com 'rm /data/update.lock'
    else
        echo "距离上次上传时间太短" >> $DIRNAME_NOW/logs/main-$NOW_DAY.log
        force_update="T"
    fi
}


echo "" > $DIRNAME_NOW/logs/main-$NOW_DAY.log
while [ "1" ];do
    echo "创建监听" >> $DIRNAME_NOW/logs/main-$NOW_DAY.log
    timeout 10m fswatch -r -L -1 ~/Documents/Projects/
    code=$?
    NOW_DAY=`date "+%Y-%m-%d"`
    [[ force_download == "T" ]] && download
    [[ force_update == "T" ]] && update
    if [[ "$code" == "124" ]];then # 退出代码 124 超时，执行下载
        download
    elif [[ "$code" == "0" ]];then # 退出代码 0 检查到文件变化，执行上传
        update
    elif [[ "$code" == "127" ]];then # 退出代码 127 异常错误
        exit 127
    else
        echo "错误的任务代码 $code" >> $DIRNAME_NOW/logs/main-$NOW_DAY.log
    fi
done
